package com.banshuibao.bsb_android.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.HistoryAdapter;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.view.EditText_Clear;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DataQueryActivity extends BaseActivity implements TextWatcher, View.OnClickListener, HistoryAdapter.OnItemClickListener {

    private String tag;
    private EditText_Clear editText_clear;
    private RecyclerView recyclerView;
    private LinearLayout history;
    private TextView menu;
    private List<String> list = new ArrayList<>();
    private HistoryAdapter adapter;
    private SharedPreferences sp;
    private SharedPreferences.Editor edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_query);
        tag = getIntent().getStringExtra("tag");
        // 得到对象
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(list!=null&&list.size()>0){
            list.clear();
        }
        if(sp!=null){
            Map<String, String> map = (Map<String, String>) sp.getAll();
            for (int i = 0; i < map.size(); i++) {
                list.add(map.get(String.valueOf(i)));
            }
            if (list != null && list.size() > 0) {
                history.setVisibility(View.VISIBLE);
            } else {
                history.setVisibility(View.GONE);
            }
            adapter.setData(list);
        }
    }


    public void initView() {
        editText_clear = findViewById(R.id.et_search);
        recyclerView = findViewById(R.id.recyclerView);
        history = findViewById(R.id.history);
        menu = findViewById(R.id.menu);
    }

    public void initData() {
        switch (tag) {
            case "repository":
                editText_clear.setHint("搜索知识");
                sp = getSharedPreferences("history", MODE_PRIVATE);
                edit = sp.edit();
                break;
            case "case":
                editText_clear.setHint("搜索案例");
                sp = getSharedPreferences("case", MODE_PRIVATE);
                edit = sp.edit();
                break;
        }
        editText_clear.addTextChangedListener(this);
        menu.setOnClickListener(this);
        history.setOnClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new HistoryAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClick(this);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            menu.setText("搜索");
        } else {
            menu.setText("取消");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.history:
                showMsg();
                break;
            case R.id.menu:
                String s = menu.getText().toString().trim();
                String content = editText_clear.getText().toString().trim();
                if (TextUtils.equals(s, "搜索")) {
                    if (!isExit(content)) {
                        saveData(content);
                    }
                    adapter.notifyDataSetChanged();
                    IntentManager.goDataQueryListActivity(context,content,tag);
                } else {
                    editText_clear.setText("");
                    finish();
                }
                break;
        }

    }

    /**
     * 保存搜索内容
     *
     * @param content
     */
    private void saveData(String content) {
        if(sp == null){
            return;
        }
        Map<String, String> map = (Map<String, String>) sp.getAll();
        int size = map.size();
        if (size == 0) {
            edit.putString(String.valueOf(size), content).commit();
        } else {
            for (int i = 0; i < size; i++) {
                String content1 = map.get(String.valueOf(i));
                edit.putString(String.valueOf(i + 1), content1).commit();
            }
            edit.putString(String.valueOf(0), content);
            edit.remove(String.valueOf(10)).commit();
        }
    }

    public boolean isExit(String content) {
        if(sp == null){
            return true;
        }
        Map<String, String> map = (Map<String, String>) sp.getAll();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (TextUtils.equals(content, entry.getValue())) {
                return true;
            }
        }
        return false;
    }

    public void showMsg(){
         Dialog dialog = new AlertDialog.Builder(this).setMessage("确定删除全部历史记录?").setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                edit.clear().commit();
                history.setVisibility(View.GONE);
            }
        }).setNegativeButton("取消", null).create();
        if (!dialog.isShowing())
            dialog.show();
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = editText_clear;
            if (v != null && isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1] - 20;
            int bottom = top + v.getHeight() + 20;
            int right = left + getWindow().getDecorView().getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    @Override
    public void getData(String title) {
        editText_clear.setText(title);
        editText_clear.setSelection(title.length());
        IntentManager.goDataQueryListActivity(context,title,tag);
    }
}
